﻿/**
*    @file:    httpservice.cpp
*    @brief:
*    @author:  sanshi522@163.com
*    @date:    2024-12-23  16:27
*/

#include "httpservice.h"
#include "httprouter.h"

#include <QCoreApplication>
#include <QSettings>

QMutex HttpService::mutex;
HttpService* HttpService::instance = nullptr;


HttpService& HttpService::getInstance()
{
    if (instance == nullptr) {
        QMutexLocker locker(&mutex);
        if (instance == nullptr) {
            instance = new HttpService();
        }
    }
    return *instance;
}

void HttpService::deleteInstance()
{
    if (instance != nullptr) {
        delete instance;
        instance = nullptr;
    }
}

HttpService::HttpService(QObject *parent) : QObject(parent)
{
    qDebug() << __FUNCTION__;
    //注册类型
    qRegisterMetaType<int8_t>("int8_t");
    qRegisterMetaType<uint8_t>("uint8_t");
    qRegisterMetaType<int16_t>("int16_t");
    qRegisterMetaType<uint16_t>("uint16_t");
    qRegisterMetaType<int32_t>("int32_t");
    qRegisterMetaType<uint32_t>("uint32_t");
    qRegisterMetaType<int64_t>("int64_t");
    qRegisterMetaType<uint64_t>("uint64_t");
    httpRouter = new HttpRouter(this);
    open();
}

HttpService::~HttpService()
{
    close();
    qDebug() << __FUNCTION__;
}

bool HttpService::getAuthorizeGuard() const
{
    return httpRouter->getAuthorizeGuard();
}

void HttpService::setAuthorizeGuard(bool value)
{
    httpRouter->setAuthorizeGuard(value);
}

HttpSessionStore *HttpService::getHttpSessionStore() const
{
    return httpSessionStore;
}

void HttpService::installController(QString path, HttpController *httpController)
{
   httpRouter->installController(path,httpController);
}

void HttpService::open()
{
    QString configFileName = QCoreApplication::applicationDirPath() + "/config/httpservice.ini";
//    Configure logging into a file
    QSettings *logSettings = new QSettings(configFileName, QSettings::IniFormat, this);
    logSettings->beginGroup("logging");
    logger = new FileLogger(logSettings, 10000, this);

#ifndef QT_DEBUG
    logger->installMsgHandler();
#endif

    // Configure session store
    QSettings *sessionSettings = new QSettings(configFileName, QSettings::IniFormat, this);
    sessionSettings->beginGroup("sessions");
    httpSessionStore = new HttpSessionStore(sessionSettings, this);

    // Configure static file controller
//    QSettings *fileSettings = new QSettings(configFileName, QSettings::IniFormat, this);
//    fileSettings->beginGroup("docroot");
//    staticFileController = new StaticFileController(fileSettings, this);

    // Configure and start the TCP listener
    QSettings *listenerSettings = new QSettings(configFileName, QSettings::IniFormat, this);
    listenerSettings->beginGroup("listener");

    httpListener = new HttpListener(listenerSettings, httpRouter, this);
}

void HttpService::close()
{
    delete httpListener;
    delete httpRouter;
    delete httpSessionStore;
    logger->clear();
    delete logger;
}
